import { defineStore } from 'pinia'
import { ref } from 'vue'
import { getGroupList } from '@/service/edu/group'

export const useGroupStore = defineStore(
  'group',
  () => {
    const groups = ref<any[]>([])
    const activeIndex = ref<number>(0)
    const setGroups = async (val: any) => {
      groups.value = val
    }
    const activeGroup = async (index: number) => {
      activeIndex.value = index
    }
    const addGroup = async (val: any) => {
      groups.value.unshift(val)
    }
    const removeGroup = async (groupId: string | number) => {
      groups.value.forEach((item, index) => {
        if (item.id === groupId) {
          groups.value.splice(index, 1)
          if (activeIndex.value >= groups.value.length) {
            activeIndex.value = groups.value.length - 1
          }
        }
      })
    }
    const findGroup = async (groupId: string | number) => {
      return groups.value.find((item: any) => item.id === groupId)
    }
    const findCourseGroup = (courseId: string | number) => {
      return groups.value.filter((item: any) => item.courseId === courseId)
    }
    const updateGroup = async (val: any) => {
      const g = findGroup(val.id)
      Object.assign(g, groups.value)
    }
    const clear = async () => {
      groups.value = []
      activeIndex.value = 0
    }
    const loadGroup = async () => {
      return new Promise((resolve, reject) => {
        getGroupList()
          .then((res: any) => {
            setGroups(res.data)
            resolve({})
          })
          .catch((err) => {
            reject(err)
          })
      })
    }
    const createFriendIds = ref<any[]>([])
    const createType = ref<boolean>(false)
    const setCreateType = async (val: any) => {
      createType.value = val
    }
    const setFriendIds = async (val: any) => {
      createFriendIds.value = val
    }
    return {
      groups,
      activeIndex,
      setGroups,
      activeGroup,
      addGroup,
      removeGroup,
      findGroup,
      updateGroup,
      clear,
      loadGroup,
      createFriendIds,
      createType,
      setCreateType,
      setFriendIds,
      findCourseGroup,
    }
  },
  {
    persist: true,
  },
)
